package 网络编程.UDPECHO;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-01
 * Time: 15:51
 */
public class UDPClint {
    private DatagramSocket socket = null;
    //客户端不需要指定端口号--如果指定端口号,可能与已经有的端口号发生冲突
    public UDPClint() throws SocketException {
        //实例化socket相当于在操作系统内核里面打开了一个文件,接下来就可以接收和发送数据了
        socket = new DatagramSocket();
    }
    //客户端启动
    public void start() throws IOException {
        System.out.println("UDP回显客户端开始启动...");
        while(true){//长连接
            Scanner scan = new Scanner(System.in);
            //客户端需要通过用户在控制台上输入数据读取用户请求
            //1.从控制台上获取请求
            System.out.print("> ");
            String request = scan.nextLine();
            //2.构造请求数据报-->数据报中指定地址和端口号->要发给谁
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    0,request.getBytes().length,
                    InetAddress.getByName("127.0.0.1"),8000);
            //3.接下来将请求数据报发送给服务器
            socket.send(requestPacket);
            //构造一个空的响应数据报-->客户端接收数据后会将响应数据放入响应数据报中
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            //4.接收服务器返回的响应
            socket.receive(responsePacket);
            //5.解析响应,显示给客户端
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("req = %s; rep = %s",request,response);
            System.out.println();
        }
    }

    public static void main(String[] args) throws IOException {
        UDPClint udpClint = new UDPClint();
        udpClint.start();
    }

}
